package com.easylinkin.linkappapi.tenant.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.annotation.CommonOperateLogAnnotate;
import com.easylinkin.linkappapi.application.entity.Application;
import com.easylinkin.linkappapi.application.service.ApplicationService;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DigestUtil;
import com.easylinkin.linkappapi.openapi.service.SynchronizationLinkthingService;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant.LogModule;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.entity.TenantRefDeviceUnitDTO;
import com.easylinkin.linkappapi.tenant.entity.TenantRefPrivilegeDTO;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuming
 * @since 2020-04-14
 */
@Api(value="租户",tags={"租户"})
@RestController
@RequestMapping("/tenant")
public class LinkappTenantController {
	
	private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(LinkappTenantController.class);
	
	@Autowired
	LinkappTenantService linkappTenantService;
	@Autowired
	ApplicationService applicationService;
	
	@Value("${linkthing.saasSecret}")
	String saasSecret;

	@Resource
	private SynchronizationLinkthingService synchronizationLinkthingService;

	@ApiOperation("新增租户")
	@CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "新增租户")
	@PostMapping("/addLinkappTenant")
	public Map<String,String> addLinkappTenant(HttpServletRequest request , HttpServletResponse response,
										@RequestParam("requestId") String requestId,
										@RequestParam("tenantId") String tenantId, 
										@RequestParam("appId") String appId,
										@RequestParam("projectId") String projectId
										) {
		String headerSign = request.getHeader("H-Ca-Signature").trim();
		String appkey = request.getHeader("H-App-Key").trim();
		String signToString = requestId + "-" + tenantId + "-" + appId + "-" + projectId;
		
		QueryWrapper<Application> wrapper = new QueryWrapper<>();
        wrapper.eq("app_key", appkey);
        wrapper.eq("delete_state", 1);
        Application application = applicationService.getApplication(wrapper);
        //String sign = DigestUtil.hmacSHA256Sign(signToString,saasSecret).trim();
        String sign = DigestUtil.hmacSHA256Sign(signToString,application.getAppSecret()).trim();
        LOGGER.info("headerSign : " + headerSign);
        LOGGER.info("appkey : " + appkey);
        LOGGER.info("signToString : " + signToString);
        LOGGER.info("sign : " + sign);
        Map<String,String> map = new HashMap<String,String>();
        
        if(sign.equalsIgnoreCase(headerSign)) {
        	LinkappTenant linkappTenant = new LinkappTenant();
    		linkappTenant.setTenantId(String.valueOf(tenantId).trim());
    		linkappTenant.setAppId(String.valueOf(appId).trim());
    		linkappTenant.setAppKey(appkey);
    		List<LinkappTenant> list = linkappTenantService.selectLinkappTenantList(linkappTenant);
    		if (list.isEmpty()) {
    			linkappTenant.setProjectId(projectId);
    			LinkappTenant linkappTenantResult = linkappTenantService.addLinkappTenant(linkappTenant);
    			if(linkappTenantResult == null) {
    				map.put("code","500");
        	        map.put("message","创建异常");
					LOGGER.info("创建异常");
    			}else {
    				map.put("code","200");
        	        map.put("message","success");
        	        map.put("saasTenantId",linkappTenant.getId());
        	        map.put("initAccount",linkappTenant.getInitAccount());
					//AEP初始化设备同步--异步调用
					synchronizationLinkthingService.syncDeviceAndUnitByProject(request, linkappTenant);
    			}
    		} else {
    			map.put("code","500");
    	        map.put("message","账号重复");
    		}
        }else {
        	map.put("code","501");
	        map.put("message","认证失败");
        }
        return map;
	}

	@ApiOperation("获取携带ssoToken信息的登录链接")
    @PostMapping("/getSSOUrl")
    public Map<String,String> getSSOUrl(HttpServletRequest request , HttpServletResponse response,
								 @RequestParam("requestId") String requestId,
								 @RequestParam("appId") String appId,
								 @RequestParam("tenantId") String tenantId, 
								 @RequestParam("saasTenantId") String id,
								 @RequestParam("account") String account){
    	String headerSign = request.getHeader("H-Ca-Signature").trim();
    	String appkey = request.getHeader("H-App-Key").trim();

		return linkappTenantService.getSSOUrl(requestId, appId, tenantId, id, account, headerSign, appkey);
    }


	@ApiOperation("更新租户")
    @CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "更新租户")
    @PostMapping("/updateLinkappTenant")
    public RestMessage updateLinkappTenant(@RequestBody LinkappTenant linkappTenant) {
    	Assert.notNull(linkappTenant.getId(), "租户编号不能为空");
        return RestBuilders.successBuilder().success(linkappTenantService.updateLinkappTenant(linkappTenant)).build();
    }

	@ApiOperation("逻辑删除租户")
    @CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "逻辑删除租户")
    @GetMapping("/deleteLinkappTenant/{tenantId}")
    public RestMessage deleteLinkappTenant(@PathVariable String tenantId) {
    	//逻辑删除字段设为删除标识
    	LinkappTenant linkappTenant = new LinkappTenant();
    	linkappTenant.setId(tenantId);
    	linkappTenant = linkappTenantService.selectLinkappTenant(linkappTenant);
    	Assert.notNull(linkappTenant, "租户不能为空");
    	linkappTenant.setStatus("0");
        return RestBuilders.successBuilder().success(linkappTenantService.updateLinkappTenant(linkappTenant)).build();
    }

    @ApiOperation("查询租户列表")
    @PostMapping("/selectLinkappTenantList")
    public RestMessage selectLinkappTenantList(@RequestBody LinkappTenant linkappTenant) {
        return RestBuilders.successBuilder().data(linkappTenantService.selectLinkappTenantList(linkappTenant)).build();
    }
    
    @ApiOperation("查询租户列表-分页")
    @PostMapping("/selectLinkappTenantPage")
	public RestMessage selectLinkappTenantPage(@RequestBody RequestModel<LinkappTenant> requestModel) {
        Assert.notNull(requestModel.getCustomQueryParams(), "customQueryParams 不能为空");
        Assert.notNull(requestModel.getPage(), "page 不能为空");
        IPage<LinkappTenant> record = linkappTenantService.selectLinkappTenantPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder().data(record).build();
    }
    
    @ApiOperation("查询租户-单个")
    @PostMapping("/selectLinkappTenant")
    public RestMessage selectLinkappTenant(@RequestBody LinkappTenant linkappTenant) {
        return RestBuilders.successBuilder().data(linkappTenantService.selectLinkappTenant(linkappTenant)).build();
    }

	@ApiOperation("租户个性化配置")
    @CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "租户个性化配置")
    @PostMapping("/tenant2Personality")
    public RestMessage tenant2Personality(@RequestBody LinkappTenant linkappTenant) {
        return RestBuilders.successBuilder().data(linkappTenantService.tenant2Personality(linkappTenant)).build();
    }

	@ApiOperation("根据租户ID获取关联的设备型号集合")
    @GetMapping("/selectDeviceUnitByTenant/{tenantId}")
	public RestMessage selectDeviceUnitByTenant(@PathVariable String tenantId) {
		return RestBuilders.successBuilder().data(linkappTenantService.selectDeviceUnitByTenant(tenantId)).build();
	}

	@ApiOperation("租户关联型号")
	@PostMapping("/tenant2DeviceUnits")
	@CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "租户关联型号")
	public RestMessage tenant2DeviceUnits(@RequestBody TenantRefDeviceUnitDTO tenantRefDeviceUnitDTO) {
		linkappTenantService.tenant2DeviceUnits(tenantRefDeviceUnitDTO.getTenant(), tenantRefDeviceUnitDTO.getDeviceUnits());
        return RestBuilders.successMessage();
    }

	@ApiOperation("根据租户ID获取关联的菜单权限数据")
	@GetMapping("/selectPrivilegeByTenant/{tenantId}")
	public RestMessage selectUserByRole(@PathVariable String tenantId, @RequestParam(value = "type", required = false) Integer type) {
		return RestBuilders.successBuilder().data(linkappTenantService.selectPrivilegeByTenant(tenantId, type)).build();
	}

	@ApiOperation("租户关联权限")
	@PostMapping("/tenant2Privileges")
	@CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "租户关联权限")
	public RestMessage tenant2Privileges(@RequestBody TenantRefPrivilegeDTO tenantRefPrivilegeDTO) {
		linkappTenantService.tenant2Privileges(tenantRefPrivilegeDTO);
        return RestBuilders.successMessage();
    }
    

	//未使用
	@ApiOperation("未使用")
	@GetMapping("/selectTenantPrivilegeByUser/{userId}")
	public RestMessage selectTenantPrivilegeByUser(@PathVariable String userId) {
		return RestBuilders.successBuilder().data(linkappTenantService.selectTenantPrivilegeByUser(userId)).build();
	}

	@ApiOperation("解锁租户")
	@GetMapping("/unlockTenant/{id}")
	@CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "解锁租户")
	public RestMessage unlock(@PathVariable String id) {
		return RestBuilders.successBuilder().data(linkappTenantService.unlockTenant(id)).build();
	}

	@ApiOperation("冻结租户")
	@GetMapping("/lockTenant/{id}")
	@CommonOperateLogAnnotate(module = LogModule.TENANT, desc = "冻结租户")
	public RestMessage lockTenant(@PathVariable String id) {
		return RestBuilders.successBuilder().data(linkappTenantService.lockTenant(id)).build();
	}
    
}
